﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;

public partial class HandlerControl_RndNumber : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //  6位数字的验证码
            string str_ValidateCode = GetRandomstr(4);
            //  用于验证的Session
            Session["ImgCode"] = (str_ValidateCode);
            CreateImage(str_ValidateCode);
        }
    }

    #region 生成随机验证码
    public string GetRandomstr(int Num_Length)
    {
        string Randomstr = string.Empty;
        Random rand = new Random();

        for (int i = 0; i < Num_Length; i++)
        {
            Randomstr += rand.Next(10).ToString();
        }
        return Randomstr;
    }
    #endregion

    #region 生成随机颜色
    public Color GetRandomColor()
    {
        //  对于C#的随机数，没什么好说的
        Random RandomNum_First = new Random();
        //  阻止当前线程，以便下一个Random能进行颜色渲染
        System.Threading.Thread.Sleep(RandomNum_First.Next(50));
        Random RandomNum_Sencond = new Random();

        //  为了在白色背景上显示，尽量生成深色
        int int_Red = RandomNum_First.Next(256);
        int int_Green = RandomNum_Sencond.Next(256);
        int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
        int_Blue = (int_Blue > 255) ? 255 : int_Blue;

        return Color.FromArgb(int_Red, int_Green, int_Blue);
    }
    #endregion

    #region 根据验证字符串生成最终带彩色的图象
    public void CreateImage(string str_ValidateCode)
    {
        //  图片宽度
        int bmpWidth = str_ValidateCode.Length * 9;
        //  图片高度
        int bmpHight = 18;

        Random newRandom = new Random();
        //  图像大小
        Bitmap theBitmap = new Bitmap(bmpWidth, bmpHight);
        Graphics theGraphics = Graphics.FromImage(theBitmap);
        //  白色背景
        theGraphics.Clear(Color.White);

        //  9pt的字体
        Font theFont = new Font("Verdana", 9);

        for (int int_index = 0; int_index < str_ValidateCode.Length; int_index++)
        {
            string str_char = str_ValidateCode.Substring(int_index, 1);
            Brush newBrush = new SolidBrush(GetRandomColor());
            Point thePos = new Point(int_index * 8, 2);
            theGraphics.DrawString(str_char, theFont, newBrush, thePos);
        }

        //  将生成的图片发回客户端
        MemoryStream ms = new MemoryStream();
        theBitmap.Save(ms, ImageFormat.Png);

        //  需要输出图象信息 要修改HTTP头
        Response.ClearContent();
        Response.ContentType = "image/Png";
        Response.BinaryWrite(ms.ToArray());
        theGraphics.Dispose();
        theBitmap.Dispose();
        Response.End();
    }
    #endregion
}